package com.tjsoft.demo.interceptor;

/**
 * <p>Title:ation拦截器</p>
 * <p>Description:session超时拦截</p>
 */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SessionInterceptor extends AbstractInterceptor {
	private String loginAction;

	private static final long serialVersionUID = 1L;
	
	public String getLoginAction() {
		return loginAction;
	}

	public void setLoginAction(String loginAction) {
		this.loginAction = loginAction;
	}

	@Override
	public String intercept(ActionInvocation inv) throws Exception {
		ActionContext actionContext = inv.getInvocationContext();
		HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
		//设置允许cookie跨域
		response.setHeader("P3P","CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"");
		HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
		HttpSession session = request.getSession();

		//如果是登录，则不进行判断
		String path = request.getContextPath();//获取路径
		String uri = request.getRequestURI();//获取URL
		
		String loginAction = path + this.loginAction;
		if(uri.startsWith(loginAction)){
			return inv.invoke();
		}
		boolean emptyLoginInfo = (session==null || session.getAttribute("student")==null);

		//如果session为空或用户登录信息为空，则禁止继续访问
		if(emptyLoginInfo){
			System.out.println("会话管理"+ "intercept()"+ "用户会话超时，已禁止访问"+uri);
			return "sessionTimeout";
		}
		return inv.invoke();
	}

}
